package com.xiaodao.netty.protobufexample.multiple;

import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.channels.SocketChannel;
import java.util.Random;

/**
 * Created by xiaodao
 * date: 2019/12/1
 */
public class MultipleClientHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception {
        MyDataInfo.MyMessage.DataType dataType = msg.getDataType();
        System.out.println(JSONUtil.toJsonPrettyStr(msg));
        if(dataType == MyDataInfo.MyMessage.DataType.StudentType){
            MyDataInfo.Student student = msg.getStudent();
            System.out.println(student.getName()+"- "+student.getAge() +" - "+student.getAddress());

        }else if(dataType == MyDataInfo.MyMessage.DataType.DogType){
            MyDataInfo.Dog dog = msg.getDog();
            System.out.println(dog.getName()+" - "+dog.getAge() );
        }else {
            MyDataInfo.Cat cat = msg.getCat();
            System.out.println(cat.getName()+" - "+ cat.getCity());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MyDataInfo.MyMessage builder =null;
        int i = new Random().nextInt(3);
        if(i == 0){
            builder= MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType)
                    .setStudent(MyDataInfo.Student.newBuilder()
                            .setName("我是学生").setAge(30).setAddress("from 北京").build()).build();


        }else if(i ==1){
            builder= MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.DogType)
                    .setDog(MyDataInfo.Dog.newBuilder()
                            .setName("你是狗").setAge(30).build()).build();
        }else if  (i ==2){
            builder= MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.CatType)
                    .setCat(MyDataInfo.Cat.newBuilder()
                            .setName("我是猫").setCity("🐈城市").build()).build();
        }
    ctx.writeAndFlush(builder);
    }
}
